﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using DataAccessObject;
using EntityObject;
using SharedLibraries;
using SharedLibraries.Constants;
using ThangNM_LIB.DB;
using ThangNM_LIB.FUNC;

namespace ThangNM.UserControl
{
    public partial class Media_DetailUC : System.Web.UI.UserControl
    {
        #region "Properties & Event"
        public delegate void CustomerEventHandler(object sender, CustomerEventArgs args);
        public event CustomerEventHandler ViewMessage;
        public event EventHandler BackList;

        public Int16 iFunctionType
        {
            get { return (Int16)ViewState["iFunctionType"]; }
            set { ViewState["iFunctionType"] = value; }
        }

        public MediaEO objTemp
        {
            get { return (MediaEO)ViewState["objTemp"]; }
            set { ViewState["objTemp"] = value; }
        }

        public Int16 FK_iCategoryID
        {
            get { return (ViewState["FK_iCategoryID"] == null ? Convert.ToInt16(0) : (Int16)ViewState["FK_iCategoryID"]); }
            set { ViewState["FK_iCategoryID"] = value; }
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                txtsContent.EnterMode = CKEditor.NET.EnterMode.BR;
                if (!IsPostBack)
                {
                    ToolBarUC1.ViewGroupButtonByFunction(ConstEx.funcButtonToolBar.DETAIL);
                }
            }
            catch (Exception ex)
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.ERROR, ex.Message, null));
            }
        }

        public void BindDataDetail(MediaEO objInput, Int16 iFuncType)
        {

            objTemp = objInput;
            BindData_DropDownList();
            WebEx.setSelect_DropDownList(ddlFK_iAccountID, Convert.ToString(objInput.FK_iAccountID));
            txtsTitle.Text = objInput.sTitle;
            txtsContent.Text = objInput.sContent;
            txtsDescription.Text = objInput.sDescription;
            txtsKeyword.Text = objInput.sKeyword;
            txtsLinkMedia.Text = objInput.sLinkMedia;
            txtsLinkImage.Text = objInput.sLinkImage;
            txtsLinkImageThumbnail.Text = objInput.sLinkImageThumbnail;
            txtsUrlRewrite.Text = objInput.sUrlRewrite;
            txtsUrlShort.Text = objInput.sUrlShort;
            WebEx.setText_InputDefault(txtfPriority, Convert.ToString(objInput.fPriority), "0.5");
            WebEx.setSelect_DropDownList(ddliChangefreq, Convert.ToString(objInput.iChangefreq));
            WebEx.setSelect_DropDownList(ddliRobots, Convert.ToString(objInput.iRobots));
            WebEx.setSelect_DropDownList(ddliStatus, Convert.ToString(objInput.iState));
            WebEx.setSelect_DropDownList(ddlFK_iCategoryID, Convert.ToString(objInput.FK_iCategoryID));
            WebEx.setSelect_ListCheckBox(cblFK_sFileID, objInput.FK_sFileID);
            //WebEx.setSelect_ListCheckBox(cblsSourceCode, objInput.sSourceCode);
            WebEx.setText_InputDefault(txtiLike, Convert.ToString(objInput.iLike), "0");
            WebEx.setText_InputDefault(txtiVisit, Convert.ToString(objInput.iVisit), "0");
            WebEx.setText_InputDefault(txtiComment, Convert.ToString(objInput.iComment), "0");
            WebEx.setText_InputDateTime(txttDateTimeCreate, objInput.tDateTimeCreate);
            WebEx.setText_InputDateTime(txttDateTimeModify, objInput.tDateTimeModify);
            if (objInput.FK_iCategoryID == Media_iType_C.Ung_Dung)
                WebEx.setSelect_DropDownList(ddliTool, Convert.ToString(objInput.iTool));

            iFunctionType = iFuncType;
            ViewByFunction(iFunctionType);
        }

        protected void BindData_DropDownList()
        {
            ddlFK_iAccountID.DataSource = (new ShareDAO.UserDAO()).SelectBy_bState(null);
            ddlFK_iAccountID.DataValueField = "PK_iAccountID";
            ddlFK_iAccountID.DataTextField = "sUsername";
            ddlFK_iAccountID.DataBind();

            ddliChangefreq.DataSource = GetListConstants.Changefreq_GLC();
            ddliChangefreq.DataValueField = "Key";
            ddliChangefreq.DataTextField = "Value";
            ddliChangefreq.DataBind();

            ddliRobots.DataSource = GetListConstants.Robots_GLC();
            ddliRobots.DataValueField = "Key";
            ddliRobots.DataTextField = "Value";
            ddliRobots.DataBind();

            ddliStatus.DataSource = GetListConstants.Topic_iStatus_GLC(false);
            ddliStatus.DataValueField = "Key";
            ddliStatus.DataTextField = "Value";
            ddliStatus.DataBind();


            List<Category_ZipEO> lst = (from i in CustomerCache.get_lstCategory_ZipEO()
                                        where i.iType == ConstEx.TableID_C.Media
                                        select i).ToList();
            ddlFK_iCategoryID.DataSource = lst;
            ddlFK_iCategoryID.DataValueField = "PK_iCategoryID";
            ddlFK_iCategoryID.DataTextField = "sName";
            ddlFK_iCategoryID.DataBind();

            cblFK_sFileID.DataSource = (new FileDAO()).SelectBy_iState(Topic_iStatus_C.All);
            cblFK_sFileID.DataValueField = "PK_iFileID";
            cblFK_sFileID.DataTextField = "sName";
            cblFK_sFileID.DataBind();

            //cblsSourceCode.DataSource = GetListConstants.Topic_sCode_GLC();
            //cblsSourceCode.DataValueField = "Key";
            //cblsSourceCode.DataTextField = "Value";
            //cblsSourceCode.DataBind();

            ddliTool.DataSource = CategoryEx.Media_iTool();
            ddliTool.DataValueField = "Key";
            ddliTool.DataTextField = "Value";
            ddliTool.DataBind();
            ddliTool.SelectedValue = "0";
        }

        protected bool CheckInput()
        {
            string strNull = "";
            if (string.IsNullOrEmpty(txtsTitle.Text) == true)
            {
                strNull += ", " + lblsTitle.Text;
                txtsTitle.Focus();
            }
            if (string.IsNullOrEmpty(txtsLinkImage.Text) == true)
            {
                strNull += ", " + lblsLinkImage.Text;
                txtsLinkImage.Focus();
            }
            if (string.IsNullOrEmpty(txtsLinkImageThumbnail.Text) == true)
            {
                strNull += ", " + lblsLinkImageThumbnail.Text;
                txtsLinkImageThumbnail.Focus();
            }
            //if (string.IsNullOrEmpty(txtsDescription.Text) == true)
            //{
            //    strNull += ", " + lblsDescription.Text;
            //    txtsDescription.Focus();
            //}
            if (ddlFK_iCategoryID.SelectedValue == Media_iType_C.Ung_Dung.ToString() && Convert.ToInt16(objTemp.iTool) != Convert.ToInt16(ddliTool.SelectedValue))
            {
                MediaEO obj = (new MediaDAO()).SelectBy_iTool(Convert.ToInt16(ddliTool.SelectedValue));
                if (obj != null)
                {
                    setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.WARNING, String.Format("Loại ứng dụng [Mã/Tên]: [{0}/{1}] đã được sử dụng ở bài viết [Mã/Tên]: [{2}/{3}]", ddliTool.SelectedValue, ddliTool.SelectedItem.Text, obj.PK_iMediaID, obj.sName), null));
                    return false;
                }
            }

            if (String.IsNullOrEmpty(strNull))
            {
                return true;
            }
            else
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.WARNING, MessagesEx.CAC_TRUONG_BAT_BUOC_PHAI_NHAP + strNull.Substring(2).Replace(":", ""), null));
                return false;
            }
        }

        protected void GetObject(ref MediaEO _MediaEO)
        {
            try
            {
                _MediaEO.PK_iTable = ConstEx.TableID_C.Media;
                _MediaEO.PK_iSEO = objTemp.PK_iSEO;
                _MediaEO.FK_sAccount = ShareDAO.UserDAO.getPK_iAccountID(Convert.ToString(Session["secret"])).Name;
                _MediaEO.FK_iCategoryID = Convert.ToInt16(WebEx.getSelect_DropDownList(ddlFK_iCategoryID, true));
                _MediaEO.FK_sCategory = Convert.ToString(_MediaEO.FK_iCategoryID);
                _MediaEO.sTitle = Convert.ToString(txtsTitle.Text);
                _MediaEO.sKeyword = StringEx.remove_dublicate_in_string_array(txtsKeyword.Text + "," + WebEx.getSelect_DropDownList(ddlFK_iCategoryID, false));
                if (String.IsNullOrEmpty(txtsDescription.Text))
                    _MediaEO.sDescription = StringEx.Trim(StringEx.RemoveHtmlTagsUsingCharArray(txtsContent.Text));
                else
                    _MediaEO.sDescription = Convert.ToString(txtsDescription.Text);
                _MediaEO.sLinkMedia = OtherEx.getUrlStandard(txtsLinkMedia.Text);
                _MediaEO.sLinkImage = OtherEx.getUrlStandard(txtsLinkImage.Text);
                _MediaEO.sLinkImageThumbnail = OtherEx.getUrlStandard(txtsLinkImageThumbnail.Text);
                //_MediaEO.sSourceCode = Commons.getSourceCodeUse(txtsContent.Text);
                _MediaEO.sUrlRewrite = Commons.get_sUrlRewrite_sUrlShort(_MediaEO.PK_iTable, true, RewriteUrl.ConvertToUnSign(WebEx.getSelect_DropDownList(ddlFK_iCategoryID, false)), _MediaEO.sTitle);
                _MediaEO.sUrlShort = Commons.get_sUrlRewrite_sUrlShort(_MediaEO.PK_iTable, false, RewriteUrl.ConvertToUnSign(WebEx.getSelect_DropDownList(ddlFK_iCategoryID, false)), _MediaEO.sTitle);
                _MediaEO.iChangefreq = Convert.ToInt16(ddliChangefreq.SelectedValue);
                _MediaEO.iRobots = Convert.ToInt16(ddliRobots.SelectedValue);
                _MediaEO.fPriority = Convert.ToDouble(txtfPriority.Text);
                _MediaEO.FK_sFileID = WebEx.getSelect_ListCheckBox(cblFK_sFileID, true);
                _MediaEO.FK_iAccountID = ShareDAO.UserDAO.getPK_iAccountID(Convert.ToString(Session["secret"])).Version;
                _MediaEO.sContent = Convert.ToString(txtsContent.Text);
                _MediaEO.iStatus = Convert.ToInt16(ddliStatus.SelectedValue);
                _MediaEO.bStatus = ConvertEx.Convert_iStatus_bStatus(_MediaEO.iStatus);
                if (_MediaEO.FK_iCategoryID == Media_iType_C.Ung_Dung)
                {
                    _MediaEO.sUrlRewrite = Commons.get_sUrlRewrite_sUrlShort(ConstEx.TableID_C.Tool, true, null, _MediaEO.sTitle);
                    _MediaEO.iTool = Convert.ToInt16(ddliTool.SelectedValue);
                }
            }
            catch (Exception ex)
            {
                _MediaEO = null;
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.ERROR, ex.Message, null));
            }
        }

        protected void ViewByFunction(Int16 iFuncType)
        {
            setEnableAllInput();
            switch (iFuncType)
            {
                case ConstEx.FunctionType.Insert:
                    ddlFK_iCategoryID.Enabled = true;
                    ToolBarUC1.ViewButtonByFunction(iFunctionType);
                    break;
                case ConstEx.FunctionType.Update: break;
                case ConstEx.FunctionType.Delete: break;
                case ConstEx.FunctionType.View:
                    if (objTemp.FK_iCategoryID == Media_iType_C.Ung_Dung)
                    {
                        lbliTool.Visible = true;
                        lbliTool1.Visible = true;
                        ddliTool.Visible = true;
                        ddlFK_iCategoryID.Enabled = false;
                    }
                    ToolBarUC1.ViewButtonByFunction(iFunctionType);
                    break;
            }
            ToolBarUC1.btnPreview.Visible = true;
        }

        protected void setEnableAllInput()
        {
            ddlFK_iAccountID.Enabled = false;
            txttDateTimeCreate.Enabled = false;
            txttDateTimeModify.Enabled = false;
            txtiLike.Enabled = false;
            txtiVisit.Enabled = false;
            txtiComment.Enabled = false;
            txtsUrlRewrite.Enabled = false;
            txtsUrlShort.Enabled = false;
            //cblsSourceCode.Enabled = false;
            lbliTool.Visible = false;
            lbliTool1.Visible = false;
            ddliTool.Visible = false;
        }

        protected void EventButtonToolBar_Click(object sender, CustomerEventArgs e)
        {
            if (e.iType != ConstEx.funcButtonToolBar.BACK_LIST && (new ShareDAO.UserDAO()).SelectBy_sPermission(Session["secret"], Convert.ToString(Request.Url.AbsolutePath), e.iType) == false)
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.DANGER, MessagesEx.Khong_Co_Quyen_Truy_Cap, null));
                Commons.setAccessDenied(Page, null);
                return;
            }
            switch (e.iType)
            {
                case ConstEx.funcButtonToolBar.INSERT_LIST: break;
                case ConstEx.funcButtonToolBar.INSERT_ITEM:
                    InsertItem();
                    break;
                case ConstEx.funcButtonToolBar.UPDATE_ITEM:
                    UpdateItem();
                    break;
                case ConstEx.funcButtonToolBar.DELETE_LIST: break;
                case ConstEx.funcButtonToolBar.DELETE_ITEM:
                    DeleteItem();
                    break;
                case ConstEx.funcButtonToolBar.REFRESH_LIST: break;
                case ConstEx.funcButtonToolBar.EXPORT_EXCEL: break;
                case ConstEx.funcButtonToolBar.RESET_FORM:
                    ResetForm();
                    break;
                case ConstEx.funcButtonToolBar.PREVIEW_TOPIC:
                    Response.Cookies["preview"].Expires = DateTime.Now.AddDays(1);
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "preview", "window.open('http://nguyenmanhthang.net/admin/ws_ajax.aspx','_blank');", true);
                    break;
                case ConstEx.funcButtonToolBar.BACK_LIST:
                    if (BackList  != null)
                        BackList(this ,null);
                    break;
            }
        }

        protected void InsertItem()
        {
            try
            {
                if (CheckInput() == true)
                {
                    MediaEO _MediaEO = new MediaEO();
                    GetObject(ref _MediaEO);
                    if (_MediaEO == null)
                        return;
                    if ((new MediaDAO()).Insert_Update_Delete(ref _MediaEO, 1) == true)
                    {
                        setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.SUCCESS, String.Format(MessagesEx.Them_Thanh_Cong_Ma_Ten, ConstEx.Table_Name_C.Media, _MediaEO.PK_iSEO, _MediaEO.sTitle), null));
                    }
                    else
                    {
                        setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.WARNING, String.Format(MessagesEx.Them_That_Bai_Ma_Ten, ConstEx.Table_Name_C.Media, _MediaEO.PK_iSEO, _MediaEO.sTitle), null));
                    }
                }
            }
            catch (Exception ex)
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.ERROR, ex.Message, null));
            }
        }

        protected void UpdateItem()
        {
            try
            {
                if (CheckInput() == true)
                {
                    MediaEO _MediaEO = new MediaEO();
                    GetObject(ref _MediaEO);
                    if (_MediaEO == null)
                        return;
                    if ((new MediaDAO()).Insert_Update_Delete(ref _MediaEO, 2) == true)
                    {
                        setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.SUCCESS, String.Format(MessagesEx.Sua_Thanh_Cong_Ma_Ten, ConstEx.Table_Name_C.Media, _MediaEO.PK_iSEO, _MediaEO.sTitle), null));
                    }
                    else
                    {
                        setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.WARNING, String.Format(MessagesEx.Sua_That_Bai_Ma_Ten, ConstEx.Table_Name_C.Media, _MediaEO.PK_iSEO, _MediaEO.sTitle), null));
                    }
                }
            }
            catch (Exception ex)
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.ERROR, ex.Message, null));
            }
        }

        protected void DeleteItem()
        {
            try
            {
                MediaEO _MediaEO = new MediaEO();
                GetObject(ref _MediaEO);
                if (_MediaEO == null)
                    return;
                if ((new MediaDAO()).Insert_Update_Delete(ref _MediaEO, 3) == true)
                {
                    setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.SUCCESS, String.Format(MessagesEx.Xoa_Thanh_Cong_Ma_Ten, ConstEx.Table_Name_C.Media, _MediaEO.PK_iSEO, _MediaEO.sTitle), null));
                }
                else
                {
                    setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.WARNING, String.Format(MessagesEx.Xoa_That_Bai_Ma_Ten, ConstEx.Table_Name_C.Media, _MediaEO.PK_iSEO, _MediaEO.sTitle), null));
                }
            }
            catch (Exception ex)
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.ERROR, ex.Message, null));
            }
        }

        protected void ResetForm()
        {
            MediaEO _MediaEO = new MediaEO();
            BindDataDetail(_MediaEO, iFunctionType);
        }

        public void setViewMessage(object sender, CustomerEventArgs args)
        {
            if (ViewMessage != null)
                ViewMessage(sender, args);
        }
    }
}